export class Fetch {
    private static baseURL = 'http://localhost:8080'

    static async get(url: string, params: any = null) {
        const options: any = {
            headers: {
                'Content-Type': 'application/json'
            }
        }
        const token = localStorage.getItem('token')
        if (token) {
            options.headers['Authorization'] = `Bearer ${token}`
        }
        let paramsURL = ''
        if (params) {
            const urlParams = new URLSearchParams()
            for (const key in params) {
                urlParams.append(key, params[key])
            }
            paramsURL = '?' + urlParams.toString()
        }
        return fetch(Fetch.baseURL + url + paramsURL, options)
    }

    static async post(url: string, body: any = null) {
        const options: any = {
            headers: {
                'Content-Type': 'application/json'
            },
            method: "POST"
        }
        const token = localStorage.getItem('token')
        if (token) {
            options.headers['Authorization'] = `Bearer ${token}`
        }
        if (body) {
            options['body'] = JSON.stringify(body)
        }
        console.log(JSON.stringify(body))
        return fetch(Fetch.baseURL + url, options)
    }

    static async delete(url: string, params: any = null) {
        const options: any = {
            headers: {
                'Content-Type': 'application/json'
            },
            method: "DELETE"
        }
        const token = localStorage.getItem('token')
        if (token) {
            options.headers['Authorization'] = `Bearer ${token}`
        }
        let paramsURL = ''
        if (params) {
            const urlParams = new URLSearchParams()
            for (const key in params) {
                urlParams.append(key, params[key])
            }
            paramsURL = '?' + urlParams.toString()
        }
        return fetch(Fetch.baseURL + url + paramsURL, options)
    }
}